<script setup>
import { ref, onMounted, watch, computed } from 'vue'

const props = defineProps({
  currentRoomId: {
    type: String,
    required: true
  },
  type: {
    type: String,
    required: true,
    validator: (value) => ['travel', 'super'].includes(value)
  }
})

const emit = defineEmits(['select-room'])

const isExpanded = ref(false)
const roomHistory = ref([])

// 计算标题
const panelTitle = computed(() => {
  return props.type === 'travel' ? '旅游攻略历史' : '超级智能体历史'
})

// 格式化房间号显示
const formatRoomId = (roomId) => {
  if (!roomId) return '未知房间'
  // 如果房间号不包含预期的前缀，直接返回原始值
  const prefix = props.type === 'travel' ? 'travel_' : 'super_'
  if (!roomId.startsWith(prefix)) return roomId
  
  // 截取前缀后的部分，只显示前8位
  const shortId = roomId.substring(prefix.length, prefix.length + 8)
  return `${props.type === 'travel' ? '旅游' : '超级'}_${shortId}...`
}

// 从localStorage加载房间历史
const loadRoomHistory = () => {
  const history = localStorage.getItem(`roomHistory_${props.type}`)
  if (history) {
    try {
      const parsed = JSON.parse(history)
      // 过滤掉不属于当前类型的房间号
      const prefix = props.type === 'travel' ? 'travel_' : 'super_'
      roomHistory.value = parsed.filter(room => room.id.startsWith(prefix))
    } catch (e) {
      console.error('Failed to parse room history:', e)
      roomHistory.value = []
    }
  }
}

// 切换展开/收起状态
const toggleExpand = () => {
  isExpanded.value = !isExpanded.value
}

// 选择房间
const selectRoom = (roomId) => {
  emit('select-room', roomId)
}

// 添加新房间到历史记录
const addToHistory = (roomId) => {
  // 检查是否已存在
  const existingIndex = roomHistory.value.findIndex(room => room.id === roomId)
  const now = new Date().toISOString()
  
  if (existingIndex !== -1) {
    // 更新访问时间
    roomHistory.value[existingIndex].lastVisited = now
  } else {
    // 添加新记录
    roomHistory.value.unshift({
      id: roomId,
      created: now,
      lastVisited: now
    })
  }
  
  // 限制历史记录数量（保留最近的10个）
  if (roomHistory.value.length > 10) {
    roomHistory.value = roomHistory.value.slice(0, 10)
  }
  
  // 保存到localStorage
  localStorage.setItem(`roomHistory_${props.type}`, JSON.stringify(roomHistory.value))
}

// 监听当前房间ID变化
watch(() => props.currentRoomId, (newId) => {
  if (newId) {
    addToHistory(newId)
  }
})

onMounted(() => {
  loadRoomHistory()
  if (props.currentRoomId) {
    addToHistory(props.currentRoomId)
  }
})
</script>

<template>
  <div class="room-history" :class="{ 'expanded': isExpanded }">
    <!-- 展开/收起按钮 -->
    <button class="toggle-button" @click="toggleExpand">
      <svg viewBox="0 0 24 24" class="toggle-icon" :class="{ 'rotated': isExpanded }">
        <path d="M15.41,16.58L10.83,12L15.41,7.41L14,6L8,12L14,18L15.41,16.58Z" fill="currentColor"/>
      </svg>
    </button>
    
    <!-- 历史记录面板 -->
    <div class="history-panel" v-show="isExpanded">
      <h3>{{ panelTitle }}</h3>
      <div class="room-list">
        <div
          v-for="room in roomHistory"
          :key="room.id"
          class="room-item"
          :class="{ 'active': room.id === currentRoomId }"
          @click="selectRoom(room.id)"
        >
          <div class="room-info">
            <span class="room-id">{{ formatRoomId(room.id) }}</span>
            <span class="room-date">{{ new Date(room.lastVisited).toLocaleDateString() }}</span>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped>
.room-history {
  position: fixed;
  left: 0;
  top: 50%;
  transform: translateY(-50%);
  display: flex;
  align-items: stretch;
  z-index: 1000;
  transition: all 0.3s ease;
}

.toggle-button {
  background: rgba(30, 30, 40, 0.9);
  border: 1px solid rgba(0, 243, 255, 0.2);
  border-left: none;
  padding: 8px;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 0 8px 8px 0;
  transition: all 0.3s ease;
}

.toggle-button:hover {
  background: rgba(40, 40, 50, 0.95);
  border-color: var(--neon-blue);
}

.toggle-icon {
  width: 24px;
  height: 24px;
  color: var(--neon-blue);
  transition: transform 0.3s ease;
}

.toggle-icon.rotated {
  transform: rotate(180deg);
}

.history-panel {
  background: rgba(30, 30, 40, 0.95);
  border: 1px solid rgba(0, 243, 255, 0.2);
  border-left: none;
  width: 300px;
  padding: 16px;
  overflow-y: auto;
  max-height: 80vh;
}

.history-panel h3 {
  color: #fff;
  margin: 0 0 16px;
  font-size: 1.2em;
  text-align: center;
}

.room-list {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.room-item {
  padding: 12px;
  background: rgba(40, 40, 50, 0.8);
  border: 1px solid rgba(0, 243, 255, 0.1);
  border-radius: 6px;
  cursor: pointer;
  transition: all 0.3s ease;
}

.room-item:hover {
  background: rgba(50, 50, 60, 0.9);
  border-color: var(--neon-blue);
  transform: translateX(4px);
}

.room-item.active {
  background: rgba(0, 243, 255, 0.1);
  border-color: var(--neon-blue);
}

.room-info {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.room-id {
  color: #fff;
  font-family: 'JetBrains Mono', monospace;
  font-size: 0.9em;
  word-break: break-all;
}

.room-date {
  color: #aaa;
  font-size: 0.8em;
}

@media (max-width: 768px) {
  .history-panel {
    width: 250px;
  }
  
  .toggle-button {
    padding: 6px;
  }
  
  .toggle-icon {
    width: 20px;
    height: 20px;
  }
}
</style> 